#!C:\Python31\python
# coding=utf-8
import cgitb, os, sys, cgi
from http import cookies;
cgitb.enable();
from mako.template import Template;
from mako.lookup import TemplateLookup;


class HTTPLib:
	def __init__(self):
		self.cookie = cookies.SimpleCookie()
		self.form = cgi.FieldStorage(keep_blank_values=True);
		self.content_type = 'text/html';
		self.charset = 'utf-8';
		self.header = '';
		self.mylookup = TemplateLookup(
			directories=['templates/'],
		   	input_encoding='utf-8',
		   	output_encoding='utf-8',
		   	encoding_errors='replace')

	def SetContentType(self, content_type):
		self.content_type = content_type;

	def SetCookie(self, key, val):
		self.cookie[key] = val;

	def SetCharset(self, charset):
		self.charset = charset;

	def AddHeaderParam(self, line):
		self.header += line + ';\r\n';

	def GetCookie(self, key):
		if (key in self.cookie): 
			return self.cookie[key];
		return None;

	def PrintBytes(self, result):
		sys.stdout.buffer.write(result);

	def PrintStdout(self, result):
		sys.stdout.buffer.write(bytes(result, 'utf8'));

	def PrintHeader(self):
		self.PrintStdout('Content-Type:' + self.content_type + ';charset=' + self.charset + ';\r\n');
		self.PrintStdout(self.cookie.output() + '\r\n');
		self.PrintStdout(self.header);
		self.PrintStdout('\r\n');

	def Print(self, filename, **keywords):
		# Print html with use of templates.
		self.PrintHeader();
		mytemplate = self.mylookup.get_template(filename);
		self.PrintBytes(mytemplate.render(**keywords));

	def PrintSimpleHTML(self, body):
		self.PrintHeader();
		self.PrintStdout('<html><head></head><body>' + body + '</body></html>');
		
	def SendFile(self, filename):
		self.SetContentType('application/x-unknown')
		self.AddHeaderParam('Content-Disposition:' + os.path.basename(filename));
		self.PrintHeader();
		self.PrintStdout(open(filename, "rb").read());

	def GetValue(self, key):
		if key in self.form:
			return self.form[key].value;
		return None;

	def GetFile(self, key):
		if key in self.form:
			return self.form[key];
		return None;	

